﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ZK.Common;

namespace ZK.HardWareBLL
{
    /// <summary>
    /// 
    /// 托利多T800
    /// </summary>
    public class ToledoT800WagonBalanceBLL
    {
        SerialPort serialPort;
        HaredWareCommonM haredWareCommonM;
        public double nowWeight;
        List<double> weightList = new List<double>();
        /// <summary>
        /// 稳定的数据
        /// </summary>
        public double wdsj = 0;
        int weightCount = 8;
        public ToledoT800WagonBalanceBLL()
        {
            nowWeight = 0;
            serialPort = new SerialPort();
            haredWareCommonM = Common.IConfig.GetSetwagonBalance;
            Open();
        }

        public void Open()
        {
            try
            {
                if (!serialPort.IsOpen)
                {
                    serialPort.PortName = haredWareCommonM.PortName;
                    serialPort.BaudRate = Convert.ToInt32(haredWareCommonM.BaudRate);
                    serialPort.Parity = Parity.Even;
                    serialPort.DataBits = Convert.ToInt32(haredWareCommonM.DataBits);
                    serialPort.StopBits = StopBits.One;
                    //ComDevice.ReadBufferSize = 20;
                    serialPort.Open();
                    serialPort.DataReceived += SerialPort_DataReceived;
                    // ComDevice.ErrorReceived += ComDevice_ErrorReceived;
                    serialPort.ReceivedBytesThreshold = 36;
                    serialPort.DtrEnable = true;
                }
            }
            catch (Exception ex)
            {

                Common.Log4.LogManage.WriteErr(ex.ToString());
                DelegateHelper.InfoMessageEvent?.Invoke(ex.Message);
            }
        }

        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] bytes = new byte[serialPort.BytesToRead];
            serialPort.Read(bytes, 0, serialPort.BytesToRead);
            //  Common.Log4.LogManage.WriteInfo(string.Join("-", bytes));
            byte[] bbz = null;
            for (int i = 0; i < bytes.Length; i++)
            {
                if (bytes[i] == 2)
                {
                    bbz = bytes.Skip(i).Take(18).ToArray();
                    goto A;
                }
            }
        A:
            if (bbz != null)
            {
                double weight = GetWeight(bbz);
                weightAdd(weight);
                if ((weight != nowWeight) && (weight != -1))
                {
                    nowWeight = weight;
                    DelegateHelper.ToledoEvent?.Invoke(GetWeight(bbz));
                }
            }
        }

        /// <summary>
        /// 添加地磅数据列表
        /// </summary>
        /// <param name="w"></param>
        void weightAdd(double w)
        {
            //Common.Log4.LogManage.WriteInfo("weightAdd 个数 " + weightList.Count().ToString());
            if (weightList.Count > (weightCount - 1))
            {
                weightList.RemoveAt(0);
            }
            weightList.Add(w);
        }
        /// <summary>
        /// 判断数据是否正常
        /// </summary>
        public void JudgeWeightIs()
        {
            // Common.Log4.LogManage.WriteInfo("JudgeWeightIs");
            double wAreave = weightList.Average();
            // Common.Log4.LogManage.WriteInfo("平均数 " + string.Join(",", weightList));
            if (weightList.Where(p => p == wAreave).Count() == weightCount)
            {
                wdsj = wAreave;
                return;
            }
            else
            {
                Thread.Sleep(200);
                JudgeWeightIs();
            }
        }

        private double GetWeight(byte[] bytes)
        {
            // Common.Log4.LogManage.WriteInfo(string.Join("-", bytes));
            if (bytes.Length == 18 && (bytes[0] == 2) && (bytes[16] == 13))
            {
                var number = 0;
                number += bytes[3] > 48 ? (bytes[3] - 48) * 100000 : 0;
                number += bytes[4] > 48 ? (bytes[4] - 48) * 10000 : 0;
                number += bytes[5] > 48 ? (bytes[5] - 48) * 1000 : 0;
                number += bytes[6] > 48 ? (bytes[6] - 48) * 100 : 0;
                number += bytes[7] > 48 ? (bytes[7] - 48) * 10 : 0;
                number += bytes[8] > 48 ? (bytes[8] - 48) : 0;
                return (double)number / 100;
                //return number;
            }
            else
            {
                Common.Log4.LogManage.WriteErr("获取地磅数据长度有误 errDate:" + string.Join("-", bytes));
                return -1;
            }
        }

        ~ToledoT800WagonBalanceBLL()
        {
            try
            {
                if (serialPort.IsOpen)
                {
                    serialPort.Close();
                }
            }
            catch (Exception ex)
            {

                Common.Log4.LogManage.WriteErr(ex.ToString());
            }
        }
    }
}
